import { HttpParams } from '@angular/common/http';
import { ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { ModalHelper, _HttpClient, SettingsService } from '@delon/theme';
import * as moment from 'moment';
import { NzMessageService } from 'ng-zorro-antd/message';

@Component({
  selector: 'app-business-items-indicate',
  templateUrl: './items-indicate.component.html'
})
export class BusinessItemsIndicateComponent implements OnInit {
  url = `api/items_indicates`;
  isAdmin = false;
  q: {
    companyId: number;
    shopId: number;
    skuType: string;
    skuTypeValue: string;
    dateType: number;
    dateVal: string;
    // sortColumn: string;
    // sortMode: string;
  } = {
    skuType: 'itemNo',
    skuTypeValue: '',
    shopId: 0,
    companyId: 0,
    dateType: 1,
    dateVal: moment().subtract(1, 'days').format('YYYY-MM-DD')
  };
  shops = [];
  shopMap = {};
  companyMapFull = {};
  loading = false;
  sku_type = [
    { index: 'itemNo', text: '商品货号' },
    { index: 'itemId', text: '商品ID' },
    { index: 'itemName', text: '商品名称' }
  ];
  listOfData = [];
  total = 0;
  ps = 30;
  pi = 1;
  scrollX = '100vw';
  statistics_date = this.q.dateVal;
  dateTypeOptions = [
    { index: 1, text: '昨日' },
    { index: 2, text: '近7天' },
    { index: 3, text: '近30天' },
    { index: 4, text: '日' },
    { index: 5, text: '月' }
  ];
  columns: {
    A: boolean;
    B: boolean;
    C: boolean;
    D: boolean;
    E: boolean;
    F: boolean;
    G: boolean;
    H: boolean;
    I: boolean;
    J: boolean;
    K: boolean;
    L: boolean;
    M: boolean;
  } = {
    A: true,
    B: true,
    C: true,
    D: true,
    E: true,
    F: false,
    G: true,
    H: true,
    I: false,
    J: true,
    K: true,
    L: true,
    M: false
  };

  constructor(
    private http: _HttpClient,
    private modal: ModalHelper,
    private msgSrv: NzMessageService,
    private router: Router,
    private cdr: ChangeDetectorRef,
    private settingService: SettingsService
  ) {
    //console.log(this.settingService.user.ID);
    if (this.settingService.user.ID == 1) {
      this.isAdmin = true;
    }
    this.loadCompanies();
    this.loadShops();
  }

  ngOnInit(): void {
    this.loadDataFromServer(this.pi, this.ps, this.q);
  }

  loadShops(companyID: number = 0): void {
    //let uri = `api/shop_map`;
    let uri = `api/shop_map_full`;
    this.http.get(uri, { companyId: companyID }).subscribe(res => {
      this.shops = res.data['shops'];
      for (let i = 0; i < this.shops.length; i++) {
        // @ts-ignore
        this.shopMap[this.shops[i]['shop_id']] = this.shops[i]['fordeal_shop_name'];
        this.companyMapFull[this.shops[i]['shop_id']] = this.shops[i]['company_name'];
      }
    });
  }

  loadDataFromServer(pageIndex: number, pageSize: number, s_params: any): void {
    this.loading = true;
    let params = new HttpParams().append('pi', `${pageIndex}`).append('ps', `${pageSize}`).appendAll(s_params);
    this.http.get(`${this.url}`, params).subscribe(res => {
      if (res.err_code != 0) {
        this.msgSrv.error(res.msg);
      }
      this.listOfData = res.data.list;
      this.total = res.data.total;
      this.loading = false;
    });
  }

  search() {
    this.loading = true;
    this.pi = 1;
    this.ps = 30;
    this.loadDataFromServer(this.pi, this.ps, this.q);
    this.loading = false;
  }

  pageIndexChange(pageIndex: number) {
    this.loadDataFromServer(pageIndex, this.ps, this.q);
  }

  pageSizeChange(pageSize: number) {
    this.loadDataFromServer(this.pi, pageSize, this.q);
  }

  dateTypeChange(value: number) {
    this.q.dateVal = '';
    let yesterday = moment().subtract(1, 'days').format('YYYY-MM-DD');
    if (value == 1) {
      this.statistics_date = yesterday;
      this.q.dateVal = this.statistics_date;
      this.loadDataFromServer(this.pi, this.ps, this.q);
    } else if (value == 2) {
      this.statistics_date = `${moment().subtract(7, 'days').format('YYYY-MM-DD')}~${yesterday}`;
      this.q.dateVal = this.statistics_date;
      this.loadDataFromServer(this.pi, this.ps, this.q);
    } else if (value == 3) {
      this.statistics_date = `${moment().subtract(30, 'days').format('YYYY-MM-DD')}~${yesterday}`;
      this.q.dateVal = this.statistics_date;
      this.loadDataFromServer(this.pi, this.ps, this.q);
    }
  }

  datePickerChange(value: any) {
    if (this.q.dateType == 4) {
      this.q.dateVal = moment(value).format('yyyy-MM-DD');
    } else if (this.q.dateType == 5) {
      this.q.dateVal = moment(value).format('yyyy-MM');
    }
    this.statistics_date = this.q.dateVal;
    this.loadDataFromServer(this.pi, this.ps, this.q);
  }

  view(shopId: number, itemId: number) {
    console.log('redirect');
    this.router.navigate([`/business/ware-analysis`], {
      queryParams: {
        shopId: shopId,
        itemId: itemId,
        dateType: this.q.dateType,
        dateVal: this.q.dateVal
      }
    });
  }

  companyList = [];
  loadCompanies(): void {
    this.http.get(`api/company_map`).subscribe(res => {
      this.companyList = res.data;
    });
  }
  companyChange(companyID: number) {
    this.loadShops(companyID);
    this.cdr.detectChanges();
  }

  getTime(timestamp: string) {
    if (timestamp && timestamp != '') {
      var date = new Date(parseInt(timestamp) * 1000);
      let Y = date.getFullYear(),
        M = date.getMonth() + 1 < 10 ? `0${date.getMonth() + 1}` : date.getMonth() + 1,
        D = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate(),
        h = date.getHours() < 10 ? `0${date.getHours()}` : date.getHours(),
        m = date.getMinutes() < 10 ? `0${date.getMinutes()}` : date.getMinutes(),
        s = date.getSeconds() < 10 ? `0${date.getSeconds()}` : date.getSeconds();
      timestamp = `${Y}-${M}-${D} ${h}:${m}:${s}`;
    }
    return timestamp;
  }
}
